package com.bullsora.kindlerss.model;

import org.hibernate.validator.constraints.NotBlank;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;

import javax.persistence.CascadeType;
import javax.persistence.EntityListeners;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.bullsora.kindlerss.model.AppUser.getAppUserDependentQuery;

@RooJavaBean
@RooToString
@RooJpaActiveRecord
@EntityListeners(AppUser.AppUserOwnedEntityListener.class)
public class Feed implements AppUser.AppUserOwnedEntity {

  @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
  @Valid
  private FeedUrl url;

  @Transient
  private transient Set<FeedEntry> newEntries = new HashSet<FeedEntry>();

  @NotBlank
  @Size(max = 30)
  private String shortName;

  @ManyToOne
  private AppUser appUser;


  public static List<Feed> findAllFeeds() {
    return getAppUserDependentQuery("SELECT o FROM Feed o", "o", Feed.class).getResultList();
  }

  public static List<Feed> findFeedEntries(int firstResult, int maxResults) {
    return getAppUserDependentQuery("SELECT o FROM Feed o", "o", Feed.class)
        .setFirstResult(firstResult)
        .setMaxResults(maxResults)
        .getResultList();
  }

  public static long countFeeds() {
    return getAppUserDependentQuery("SELECT COUNT(o) FROM Feed o", "o", Long.class).getSingleResult();
  }

  public static Feed findFeed(Long id) {
    if (id == null) return null;
    return getAppUserDependentQuery("SELECT o FROM Feed o where o.id = :id ", "o", Feed.class)
        .setParameter("id", id)
        .getSingleResult();
  }


  public Set<FeedEntry> getNewEntries() {
    return newEntries;
  }

  public void setNewEntries(Set<FeedEntry> newEntries) {
    this.newEntries = newEntries;
  }
}
